﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using System.Management;
using System.Security.Cryptography;
using System.Text;

namespace ForestFirePrevention
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                FileInfo FI = new FileInfo(@"etc\key.conf");
                string Fingerprint = GetFingerprint();

                if (!FI.Exists)
                {
                    ShowFingerprint(Fingerprint, "软件未注册！");
                    return;
                }
                StreamReader SR = new StreamReader(FI.FullName);
                string FingerprintBase64 = SR.ReadLine();
                SR.Close();
                string privatekey = @"<RSAKeyValue><Modulus>yZFgSP7w9aV9d1/WK3+n0YQcIUvF72orY13aXQl+Vv4MZVFlDd/wEUg+4hRvVSJJnCcyNYX6nNuAz4GoFgq4QrpXW8PAc0oo7Qc6KyKjakdYbV/9+RsCdxlekD6ej0yo7r3zhi1QSENVq+xbQut7uDG5uq1DNkpsbbAtqvxozQs=</Modulus><Exponent>AQAB</Exponent><P>9ytEpdIP8n8q+mfRfIFCv0OOJcdd2uCzR0FKgvrseWgEEAQKklkfh6kGl7bL8d9pkzB8ebjcUQQSjDOBV/CpFw==</P><Q>0MUEXPidnNgrH0d/D1RqhqcZMp4zO6rvqydXOK0AWYrYtGGpr1EkuqA65tZrSfvGSbNM6vWEOrxlUSD7mwIMLQ==</Q><DP>lnFdnViYoE9LB5M9bPz4dZZW5SPOOrVeKdbR1ZuJZ/Qp1N3A2Ycpq9bzzlBTHmuPxSlT+nrMjvtdlrya074GDQ==</DP><DQ>d+9XbFnfokWFsHiQhCwI7sZ8cVn1MOgou/jj4Mlyk/5yNF6O7wr8wMJgVFEGXgBoj9qT67+UcXHd+tep9AkfGQ==</DQ><InverseQ>2y020lTvgQkTHE+R9UU8R+zJFzlup3PrkS534W0OUThxzO6yaQByRbDzWGbzBzzVnvFA0FtFCZE6gxub7QKn2A==</InverseQ><D>ospPSgTkFHBISV3UOaNKpNKeaWGqBTbovcKxtcwSBi39UuKOy8rdNwfzCWHZnJcpffzF9yYyhfZdLLmZR9v2fTWIe0Pt+nhsBwnnx6xdktURlArUUsWwNp0UqEGK8SN9IT08BZrcpIU4QshVzWhVLWXet5SX55yrgsh78Eth3ck=</D></RSAKeyValue>";

                string FingerprintRSA = RSADecrypt(privatekey, FingerprintBase64);

                if (FingerprintRSA != Fingerprint)
                {
                    ShowFingerprint(Fingerprint, "软件已过期！");
                    return;
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "注册失败！");
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }

        static void ShowFingerprint(string Fingerprint, string Message)
        {
            Label lMessage = new Label();
            lMessage.Location = new System.Drawing.Point(12, 12);
            lMessage.Text = Message;

            TextBox tBFingerprint = new TextBox();
            tBFingerprint.CharacterCasing = CharacterCasing.Upper;
            tBFingerprint.Location = new System.Drawing.Point(14, 28);
            tBFingerprint.Font = new System.Drawing.Font("宋体", 24F);
            tBFingerprint.Size = new System.Drawing.Size(358, 44);
            tBFingerprint.MaxLength = 16;
            tBFingerprint.ReadOnly = true;
            tBFingerprint.TextAlign = HorizontalAlignment.Center;
            tBFingerprint.Text = Fingerprint;

            Form FormFingerprint = new Form();
            FormFingerprint.AutoScaleMode = AutoScaleMode.Dpi;
            FormFingerprint.ClientSize = new System.Drawing.Size(394, 97);
            FormFingerprint.FormBorderStyle = FormBorderStyle.FixedSingle;
            FormFingerprint.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            FormFingerprint.TopMost = true;
            FormFingerprint.Text = "森林防火系统2013 - 机器码";
            FormFingerprint.Icon = Properties.Resources.fire;
            FormFingerprint.ShowInTaskbar = false;
            FormFingerprint.MaximizeBox = false;
            FormFingerprint.MinimizeBox = false;

            FormFingerprint.Controls.Add(tBFingerprint);
            FormFingerprint.Controls.Add(lMessage);

            FormFingerprint.ShowDialog();
        }

        static string GetFingerprint()
        {
            string fingerprint = string.Empty;
            //获取CPU序列号
            ManagementObjectSearcher MOSProcessor = new ManagementObjectSearcher("Select ProcessorID From Win32_Processor");
            ManagementObjectCollection OperatingSystems = MOSProcessor.Get();
            foreach (var OperatingSystem in OperatingSystems)
            {//获取CPU序列号
                fingerprint += OperatingSystem["ProcessorID"].ToString();
            }
            //获取网络适配器MAC地址
            ManagementObjectSearcher MOSMACAddress = new ManagementObjectSearcher("Select * From Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection MACAddresses = MOSMACAddress.Get();
            foreach (var MACAddress in MACAddresses)
            {//获取网卡MAC地址
                if (!(bool)MACAddress["IPEnabled"]) continue;
                fingerprint += MACAddress["MACAddress"].ToString().Replace(":", "");
            }
            fingerprint = fingerprint.ToUpper();
            MD5 md5 = new MD5CryptoServiceProvider();
            string password = HexToString(md5.ComputeHash(Encoding.Default.GetBytes(fingerprint)));
            return password.Substring(0, 16);
        }

        static string HexToString(byte[] hex)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hex.Length; i++)
            {
                string h = hex[i].ToString("X");
                if (h.Length == 1) h = "0" + h;
                sb.Append(h);
            }
            return sb.ToString().ToUpper();
        }

        static string RSADecrypt(string privatekey, string content)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            byte[] cipherbytes;
            rsa.FromXmlString(privatekey);
            cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false);
            return HexToString(cipherbytes);
        }
    }
}
